package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.query.RegionQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/region")
public class RegionController {
    @Autowired
    private IRegionService regionService;

    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") QueryObject qo, Model model){
        return "region/list";
    }

    @RequestMapping("/queryByParentId")
    @ResponseBody
    public List queryByParentId(RegionQueryObject qo,String type){
        List<Region> list = regionService.queryByParentId(qo);
        //通过传过来一个变量来判断是否需要转换返回的类型
        if ("tree".equals(type)){
            List<Map<String,Object>> maps = new ArrayList<>();
            for (Region region : list) {
                maps.add(region.toTreeMap());
            }
            return maps;
        }
       return list;
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Region region){
        regionService.saveOrUpdate(region);
        return "redirect:/region/list.do";
    }
    @RequestMapping("/changeState")
    public String changeState(Region region){
        regionService.changeState(region);
        return "redirect:/region/list.do";
    }
}
